package com.ruoyi.base.tool;

import javax.xml.bind.DatatypeConverter;

//自定义协议的验证
public class CHeck16 {

    public static String write(String hexString) {

        String cleanedHex = hexString.replaceAll("\\s", "");

        if (!cleanedHex.matches("[0-9a-fA-F]+") || cleanedHex.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string");
        }

        byte[] bytes = DatatypeConverter.parseHexBinary(cleanedHex);
        byte checksum = 0;

        for (byte b : bytes) {
            checksum ^= b;
        }

        return cleanedHex + String.format("%02X", checksum);
    }


    public static boolean read(String hexString) {

        String cleanedHex = hexString.replaceAll("\\s", "");

        int length = cleanedHex.length();
        String body = cleanedHex.substring(0,length-2);
        String tail = cleanedHex.substring(length-2);

        if (!body.matches("[0-9a-fA-F]+") || body.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string");
        }

        byte[] bytes = DatatypeConverter.parseHexBinary(body);
        byte checksum = 0;

        for (byte b : bytes) {
            checksum ^= b;
        }

        String format = String.format("%02X", checksum);

        if (!format.equals(tail)){
            throw new RuntimeException("设备回复数据验证失败！");
        }

        return true;

    }

}
